<?php
/**
 * Created by PhpStorm.
 * User: Hanson
 * Date: 2016/8/29
 * Time: 19:43
 */

namespace App\Service;


use App\Jobs\SaveNetworkUser;
use App\Model\NetworkInfo;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Symfony\Component\DomCrawler\Crawler;
use Cache;

class NetworkService
{

    const LOGIN_URL = 'http://ngrok.zark.in:20074/selfservice/login.jsf';

    const REGISTER_URL = 'http://ngrok.zark.in:20074/selfservice/preregister/preregister.jsf';

    public $sessionId;

    public $client;

    /**
     * @var Crawler
     */
    public $crawler;

    /**
     * @var Request
     */
    public $request;

    public function __construct()
    {
        $this->client = new Client(['cookies' => true]);
    }

    /**
     * 获取页面option、验证码
     *
     * @return array
     */
    public function getSelectOption()
    {
        $result = [];

        $select = $this->crawler->filter('.rowValueStyle')->each(function($node) use ($result){

            /**
             * @var Crawler $select
             * @var Crawler $node
             */
            $select = $node->filter('select');

            $result['options'] = $select->filter('option')->each(function($option) use ($result){
                /** @var Crawler $option */
                return $result[] = $option->text();
            });

            return $result;
        });

        return $select;
    }

    /**
     * 进入注册页面获取信息
     *
     * @return array
     */
    public function getCrawlInfo()
    {
        $this->getRegisterCrawler();

        $code = $this->getCode();

        $viewState = $this->getViewState();

        $option = Cache::get('network_option');

        if(!$option){

            $option = $this->getSelectOption();

            Cache::put('network_option', $option, Carbon::now()->addHour(24));

        }

        return ['sessionId' => $this->sessionId, 'code' => $code, 'viewState' => $viewState, 'select' => $option];
    }

    /**
     * 获取验证码
     *
     * @return string
     */
    private function getCode()
    {
        return $this->crawler->filter('td span label')->text();
    }

    /**
     * 获取页面viewState
     *
     * @return null|string
     */
    private function getViewState()
    {
        return $this->crawler->filter('input[name="javax.faces.ViewState"]')->attr('value');
    }

    /**
     * 获取页面元素
     */
    public function getRegisterCrawler()
    {
        $this->sessionId = $this->getSessionId();

        $response  = $this->client->request('get', self::REGISTER_URL . '?init=true', [
            'headers' => [
                'Cookie' => 'JSESSIONID=' . $this->sessionId
            ],
        ]);
        $content = $response->getBody()->getContents();

        $content = mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8');

        $this->crawler = new Crawler($content);
    }

    /**
     * 获取页面COOKIE
     *
     * @return mixed
     */
    private function getSessionId()
    {
        $cookie = $this->client->request('get', self::LOGIN_URL)->getHeader('Set-Cookie')[0];

        $sessionId = explode('=', explode(';', $cookie)[0])[1];

        return $sessionId;
    }


    /**
     * 开网预注册
     *
     * @param $request Request
     * @return bool
     */
    public function submit($request)
    {
        $this->request = $request;

        $result = $this->postRegister();

        if(!$result){
            return false;
        }

        dispatch(new SaveNetworkUser(array_merge($request->all(), ['openId' => \Auth::guard('wechat')->user()->open_id])));

        return true;
    }

    /**
     * post到注册页
     *
     * @return bool
     */
    private function postRegister()
    {
        $form = array_merge($this->request->all(), [
            'mainForm:confirmUserPasswd' => $this->request->get('mainForm:userPasswd'),
            'javax.faces.ViewState' => $this->request->get('javax_faces_ViewState')
        ]);

        $cookies = $form['cookies'];

        $header[] = "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
        $header[] = "Accept: text/html, application/xhtml+xml, */*";
        $header[] = "Accept-language: zh-CN";
        $header[] = "Cookie: " . 'JSESSIONID=' . $cookies;
        $post_string = http_build_query($form);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
        curl_setopt($ch, CURLOPT_URL, self::REGISTER_URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); // 模拟的header头
        curl_setopt($ch, CURLOPT_HEADER, true); // 将头部信息作为数据流输出
        $content = curl_exec($ch);
        curl_close($ch);

        if(str_contains($content, 'preregisterResult') === true){
            return true;
        }

        \Log::warning('请求参数：' . json_encode($form));

        return false;
    }

}